package com.ccteam.shared.domain.moment.comment

import android.content.Context
import androidx.paging.Pager
import androidx.paging.PagingConfig
import androidx.paging.PagingData
import androidx.paging.map
import com.ccteam.shared.api.MomentsDataSource
import com.ccteam.shared.data.moment.comment.CommentsPagingSource
import com.ccteam.shared.domain.PagingUseCase
import com.ccteam.shared.result.moment.comment.MomentReplayItem
import com.ccteam.shared.utils.EMPTY_STRING
import com.ccteam.shared.utils.transToDateReciprocal
import dagger.hilt.android.qualifiers.ApplicationContext
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.flowOf
import kotlinx.coroutines.flow.map
import javax.inject.Inject

/**
 * @author Xiaoc
 * @since 2021/3/29
 */
class CommentListDataUseCase @Inject constructor(
    @ApplicationContext private val context: Context,
    private val momentsDataSource: MomentsDataSource
): PagingUseCase<String?, MomentReplayItem>(
    Dispatchers.IO
) {

    override fun execute(parameters: String?): Flow<PagingData<MomentReplayItem>> {
        if(parameters.isNullOrEmpty()){
            return flowOf(PagingData.empty())
        }
        return Pager(
            PagingConfig(pageSize = 15,initialLoadSize = 15)
        ){
            CommentsPagingSource(parameters,momentsDataSource)
        }.flow.map { pagingData ->
            pagingData.map {
                MomentReplayItem(it.id,it.momentId,it.commentId,it.content,it.user.id, it.user.name
                    ,it.createTime.transToDateReciprocal(context),
                    it.user.photoUrl ?: EMPTY_STRING, it.toUser.id,it.toUser.name,it.type,
                    0
                )
            }
        }
    }
}